import { ref, watch } from 'vue'

const searchEngines = {
  baidu: {
    name: '百度',
    getUrl: (val: string) => `https://www.baidu.com/s?ie=UTF-8&wd=${val}`,
  },
  google: {
    name: '谷歌',
    getUrl: (val: string) => `https://www.google.com/search?q=${val}`,
  },
  "ds1.5b": {
    name: 'DS:1.5B',
    getUrl: (val: string) => `/ai?v=${val}`
  }
}

export type AllowedSearchEnginesOptions = 'baidu' | 'google' | "ds1.5b"
let CacheSelection = localStorage.getItem('searchEngineKey') as AllowedSearchEnginesOptions | null;
if (CacheSelection === null) {
  CacheSelection = 'baidu';
  localStorage.setItem('searchEngineKey', 'baidu');
}
const searchEngineKey = ref<AllowedSearchEnginesOptions>(CacheSelection)

watch(searchEngineKey, val=>{
  localStorage.setItem('searchEngineKey', val);
})

const iconSearch = ref('')
const selectSearchRef = ref<HTMLSelectElement | null>(null)
const queryText = ref('') // 添加 queryText 变量

// 执行查询操作
const query = () => {
  if (queryText.value)
    window.open(searchEngines[searchEngineKey.value].getUrl(queryText.value), '_self')
}

export default function useSearchEngine() {
  return {
    searchEngines,
    searchEngineKey,
    iconSearch,
    selectSearchRef,
    query,
    queryText, // 导出 queryText 变量
  }
}
